﻿using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using System.Data.SqlClient;

public partial class Main_Inventory_EditBOM : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    string sql = "";
    int ControlCounter = 0;
    string BOMID = "";
    List<string> LstItemName;
    List<string> LstUnit;
    List<string> LstQty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["bomid"] != null)
        {
            BOMID = Request.QueryString["bomid"].ToString();
        }

        if (!IsPostBack)
        {
            HidControl.Value = ControlCounter.ToString();
            BindDDLItem();

            LstItemName = new List<string>();
            ViewState["LstItemName"] = LstItemName;

            LstQty = new List<string>();
            ViewState["LstQty"] = LstQty;

            LstUnit = new List<string>();
            ViewState["LstUnit"] = LstUnit;
            bindselected();

        }

    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        LstItemName = (List<string>)ViewState["LstItemName"];
        LstQty = (List<string>)ViewState["LstQty"];
        LstUnit = (List<string>)ViewState["LstUnit"];
        for (int i = 0; i < LstItemName.Count; i++)
        {
            ControlCounter++;

            HtmlTableRow htrow = new HtmlTableRow();
            htrow.ID = "htrow" + ControlCounter.ToString();

            HtmlTableCell htcell1 = new HtmlTableCell();
            htcell1.ID = "htcell1" + ControlCounter.ToString();
            htcell1.Width = "19%";
            htcell1.VAlign = "Top";
            DropDownList dropdown = new DropDownList();
            dropdown.ID = LstItemName[i].ToString();
            dropdown.Width = Unit.Percentage(99);
            dropdown.AutoPostBack = true;
            dropdown.SelectedIndexChanged += new EventHandler(DropDown_SelectedIndexChanged);
            dropdown.CssClass = "dropdown";
            htcell1.Controls.Add(dropdown);


            HtmlTableCell htcell2 = new HtmlTableCell();
            htcell2.ID = "htcell2" + ControlCounter.ToString();
            htcell2.Width = "8%";
            htcell2.VAlign = "Top";
            TextBox TxtQty = new TextBox();
            TxtQty.ID = LstQty[i].ToString();
            TxtQty.Width = Unit.Percentage(99);
            TxtQty.Text = "0.00";
            //TxtQty.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
            //TxtQty.Attributes.Add("onblur", "calcQty(); calcAmt();");
            //TxtQty.AutoCompleteType = AutoCompleteType.Disabled;
            TxtQty.CssClass = "inputnumber";


            HtmlTableCell htcell3 = new HtmlTableCell();
            htcell3.ID = "htcell3" + ControlCounter.ToString();
            htcell3.Width = "14%";
            htcell3.VAlign = "Top";
            TextBox TxtUnit = new TextBox();
            TxtUnit.ID = LstUnit[i].ToString();
            TxtUnit.Width = Unit.Percentage(99);
            TxtUnit.ReadOnly = true;
            TxtUnit.CssClass = "input";
            //TxtUnit.Attributes.Add("onKeyPress", "return false");
            //TxtUnit.AutoCompleteType = AutoCompleteType.Disabled;

            htcell3.Controls.Add(TxtQty);
            htcell2.Controls.Add(TxtUnit);
            htrow.Cells.Add(htcell1);
            htrow.Cells.Add(htcell2);
            htrow.Cells.Add(htcell3);
            tblItem.Rows.Add(htrow);
//            Bind_Control(ControlCounter);
        }
    }

    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        ControlCounter++;

        HtmlTableRow htrow = new HtmlTableRow();

        HtmlTableCell htcell1 = new HtmlTableCell();
        htcell1.VAlign = "Top";
        DropDownList dropdown = new DropDownList();
        dropdown.ID = "DDLItemName" + ControlCounter.ToString();
        dropdown.SelectedIndexChanged += new EventHandler(DropDown_SelectedIndexChanged);
        dropdown.Attributes.Add("onchange", "return checkItemRepetion(this.id)");
        //dropdown.Width = Unit.Percentage(99);
        // BindAllItemDropdownlist(dropdown);
        dropdown.AutoPostBack = true;
        // dropdown.SelectedIndexChanged += new EventHandler(ddlItem_SelectedIndexChanged);
        dropdown.CssClass = "dropdown";
        dropdown.Width = Unit.Percentage(99);
        htcell1.Controls.Add(dropdown);
        LstItemName.Add(dropdown.ID);

        HtmlTableCell htcell2 = new HtmlTableCell();
        htcell2.VAlign = "Top";
        TextBox TxtQty = new TextBox();
        TxtQty.ID = "TxtQty" + ControlCounter.ToString();
        // txtQty.Width = Unit.Percentage(99);
        TxtQty.CssClass = "inputnumber";
        // txtQty.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
        // txtQty.Attributes.Add("onblur", "calcQty(); calcAmt();");
        // txtQty.AutoCompleteType = AutoCompleteType.Disabled;
        TxtQty.Width = Unit.Percentage(99);
        TxtQty.Text = "0.00";
        LstQty.Add(TxtQty.ID);

        HtmlTableCell htcell3 = new HtmlTableCell();
        htcell3.Width = "14%";
        htcell3.VAlign = "Top";
        TextBox TxtUnit = new TextBox();
        TxtUnit.ID = "TxtUnit" + ControlCounter.ToString();
        TxtUnit.Width = Unit.Percentage(99);
        TxtUnit.ReadOnly = true;
        // txtUnit.Width = Unit.Percentage(99);
        TxtUnit.CssClass = "input";
        // txtUnit.Attributes.Add("onKeyPress", "return false");
        // txtUnit.AutoCompleteType = AutoCompleteType.Disabled;

        htcell2.Controls.Add(TxtUnit);
        htcell3.Controls.Add(TxtQty);
        LstUnit.Add(TxtUnit.ID);



        htrow.Cells.Add(htcell1);
        htrow.Cells.Add(htcell2);
        htrow.Cells.Add(htcell3);
        tblItem.Rows.Add(htrow);


        ViewState["LstItemName"] = LstItemName;
        ViewState["LstQty"] = LstQty;
        ViewState["LstUnit"] = LstUnit;

        HidControl.Value = ControlCounter.ToString();
        Bind_Control(ControlCounter, false);
    }
    protected void BindDDLItem()
    {
        sql = "select ITMDESC, ITMID from IVR_ITEM Where ITMID=(select ITMID from IVR_BOM where bomid=" + BOMID + ")";
        DataTable dt1 = DU.getdata(sql);
        LblItemName.Text = dt1.Rows[0]["ITMDESC"].ToString();
        string item_id = dt1.Rows[0]["ITMID"].ToString();
        HidItemId.Value = dt1.Rows[0]["ITMID"].ToString();

        string sql1 = "select UOMSYMBOL from IVR_UOM inner join IVR_ITEM on IVR_UOM.UOMID=IVR_ITEM.PRIMARY_UOMID where IVR_ITEM.ITMID='" + item_id + "'";
        DataTable DT1 = DU.getdata(sql1);
        TxtUnitSymbol.Text = DT1.Rows[0][0].ToString();

        string sql2 = "select ITMQTY, BOMACTIVE, EDITINTRAN, BOMREMARKS from IVR_BOM Where bomid =" + BOMID;
        DataTable DT2 = DU.getdata(sql2);
        TxtQuantity.Text = DT2.Rows[0][0].ToString();
        TxtRemarks.Text = DT2.Rows[0][3].ToString();
        //lblMsg.Text = DT2.Rows[0][1].ToString();
        ChkActive.Checked = Convert.ToBoolean(DT2.Rows[0][1]);
        ChkEditTransaction.Checked = Convert.ToBoolean(DT2.Rows[0][2]);
    }

    protected void DropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList DDL = (DropDownList)sender;
        string ddid = DDL.ID.ToString().Substring(11);
        TextBox txtUnit = (TextBox)tblItem.FindControl("TxtUnit" + ddid);
        TextBox txtQty = (TextBox)tblItem.FindControl("TxtQty" + ddid);
        if (DDL.SelectedValue != "0")
        {
            string item_id = DDL.SelectedValue;
            string sql = "select UOMSYMBOL from IVR_UOM inner join IVR_ITEM on IVR_UOM.UOMID=IVR_ITEM.PRIMARY_UOMID where IVR_ITEM.ITMID='" + item_id + "'";
            DataTable DT = DU.getdata(sql);
            txtUnit.Text = DT.Rows[0][0].ToString();
        }
        else
        {
            txtUnit.Text = "";
        }
    }

    protected void Bind_Control(int rowcount, bool bindall)
    {
        
        int dlcount = 0;
        int count = Convert.ToInt32(HidControl.Value);
        //if (ViewState["prevcount"] == null)
        //{
        //    ViewState["prevcount"] = 1;
        //}
        //else
        //{
        //    ViewState["prevcount"] = count;
        //}
        //if (reload == true)
        //{
        //    dlcount = 1;
        //}
        //else
        //{

        //    dlcount = Convert.ToInt32(ViewState["prevcount"]);
        //}
        if (bindall == true)
        {
            dlcount = 1;
        }
        else
        {
            dlcount = rowcount;
        }
        for (int i = dlcount; i <= count; i++)
        {
            DropDownList DDLItm = (DropDownList)tblItem.FindControl("DDLItemName" + i.ToString());
            sql = "select ITMDESC, ITMID from IVR_ITEM where itmid!=" + HidItemId.Value + " order by ITMDESC";
            DataTable dt = DU.getdata(sql);
            DDLItm.DataSource = dt;
            DDLItm.DataTextField = "ITMDESC";
            DDLItm.DataValueField = "ITMID";
            DDLItm.DataBind();
            DDLItm.Items.Insert(0, new ListItem("-Select Item-", "0"));
        }
    }
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        try
        {
            int active = 0;
            if (ChkActive.Checked == true)
            {
                active = 1;
            }
            int EditTransaction = 0;
            if (ChkActive.Checked == true)
            {
                EditTransaction = 1;
            }
            SqlParameter[] parm ={                                 
                                  new SqlParameter("@BOMID",BOMID),
                                  new SqlParameter("@ITMID",HidItemId.Value),
                                  new SqlParameter("@ITMQTY",TxtQuantity.Text.Trim()),
                                  new SqlParameter("@BOMREMARKS", TxtRemarks.Text.Trim()),
                                  new SqlParameter("@BOMACTIVE",ChkActive.Checked),
                                  new SqlParameter("@EDITINTRAN",ChkEditTransaction.Checked),
                                  new SqlParameter("@EName",Session["username"].ToString())
                               };
            DU.executeprocedure("usp_update_IVR_BOM", parm);
            InsertBOM(BOMID);
            lblMsg.Attributes.Remove("class");
            lblMsg.Attributes.Add("class", "true");
            lblMsg.Text = "Bill oF Material created successfully...";
        }
        catch (Exception ex)
        {
            lblMsg.Attributes.Remove("class");
            lblMsg.Attributes.Add("class", "false");
            lblMsg.Text = ex.Message;
        }
    }

    protected void InsertBOM(string MainId)
    {

        int count = Convert.ToInt32(HidControl.Value);
        string sqldel = "delete IVR_BOMITEM where Bomid =" + MainId;
        DU.executesql(sqldel);
    
            for (int i = 1; i <= count; i++)
            {
                DropDownList DDL = (DropDownList)tblItem.FindControl("DDLItemName" + i.ToString());
                if (DDL.SelectedValue != "0")
                {
                    TextBox TxtQty = (TextBox)tblItem.FindControl("TxtQty" + i.ToString());
                    string sql = "select PRIMARY_UOMID from IVR_ITEM where ITMID='" + DDL.SelectedValue + "'";
                    DataTable DT = DU.getdata(sql);
                    string uomid = DT.Rows[0][0].ToString();

                    SqlParameter[] parm ={                                 
                                  new SqlParameter("@BOMID",MainId),
                                  new SqlParameter("@ITMID",DDL.SelectedValue),
                                  new SqlParameter("@ITMQTY", TxtQty.Text.Trim()),
                                  new SqlParameter("@UOMID",uomid),
                                  new SqlParameter("@CName",Session["username"].ToString())
                                     };

                    DU.executeprocedure("usp_insert_IVR_BOMITEM", parm);
                }
            }
       
    }

    protected void bindselected()
    {
        string sql = "select * from IVR_BOMITEM where BOMID =" + BOMID;
        DataTable dt = DU.getdata(sql);
        generatecontrols(dt.Rows.Count);// Generate the controls and add them to the pages
        Bind_Control(dt.Rows.Count, true); //Binding data to the dynamically generated controls
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DropDownList DDLItm = (DropDownList)tblItem.FindControl("DDLItemName" + (i + 1).ToString());
            DDLItm.SelectedValue = dt.Rows[i]["itmid"].ToString();
            TextBox TxtQty = (TextBox)tblItem.FindControl("TxtQty" + (i + 1).ToString());
            TxtQty.Text = dt.Rows[i]["ITMQTY"].ToString();
            string item_id = dt.Rows[i]["ITMID"].ToString();
            string sql1 = "select UOMSYMBOL from IVR_UOM inner join IVR_ITEM on IVR_UOM.UOMID=IVR_ITEM.PRIMARY_UOMID where IVR_ITEM.ITMID='" + item_id + "'";
            DataTable dt1 = DU.getdata(sql1);
            TextBox TxtUnit = (TextBox)tblItem.FindControl("TxtUnit" + (i + 1).ToString());
            TxtUnit.Text = dt1.Rows[0]["UOMSYMBOL"].ToString();
        }
    }

    private void generatecontrols(int count)
    {

        HidControl.Value = count.ToString();
        for (int i = 1; i <= count; i++)
        {
            HtmlTableRow htrow = new HtmlTableRow();
            HtmlTableCell htcell1 = new HtmlTableCell();
            htcell1.VAlign = "Top";
            DropDownList dropdown = new DropDownList();
            dropdown.ID = "DDLItemName" + i.ToString();
            //dropdown.SelectedIndexChanged += new EventHandler(DropDown_SelectedIndexChanged);
            dropdown.Attributes.Add("onchange", "checkItemRepetion(this.id)");
            dropdown.AutoPostBack = true;
            dropdown.CssClass = "dropdown";
            dropdown.Width = Unit.Percentage(99);
            htcell1.Controls.Add(dropdown);
            LstItemName.Add(dropdown.ID);

            HtmlTableCell htcell2 = new HtmlTableCell();
            htcell2.Width = "14%";
            htcell2.VAlign = "Top";
            TextBox TxtUnits = new TextBox();
            TxtUnits.ID = "TxtUnit" + i.ToString();
            TxtUnits.Width = Unit.Percentage(99);
            TxtUnits.ReadOnly = true;
            TxtUnits.CssClass = "input";
            htcell2.Controls.Add(TxtUnits);
            LstUnit.Add(TxtUnits.ID);

            HtmlTableCell htcell3 = new HtmlTableCell();
            htcell3.VAlign = "Top";
            TextBox TxtQty = new TextBox();
            TxtQty.ID = "TxtQty" + i.ToString();
            TxtQty.CssClass = "inputnumber";
            TxtQty.Width = Unit.Percentage(99);
            TxtQty.Text = "0.00";
            TxtQty.AutoCompleteType = AutoCompleteType.Disabled;
            htcell3.Controls.Add(TxtQty);
            LstQty.Add(TxtQty.ID);

            htrow.Cells.Add(htcell1);
            htrow.Cells.Add(htcell2);
            htrow.Cells.Add(htcell3);
            tblItem.Rows.Add(htrow);

           
            ViewState["LstItemName"] = LstItemName;
            ViewState["LstQty"] = LstQty;
            ViewState["LstUnit"] = LstUnit;
        }
    }

    protected void BtnClose_Click(object sender, EventArgs e)
    {
        Response.Redirect("BOMView.aspx");
    }
}
